package com.future.taskdemo.CompletionStage;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author Dongwei-Chen
 * @Date 2023/3/23 18:45
 * @Description 协程测试类
 */
public class CompletionStageDemo {

    public static void main(String[] args) throws InterruptedException {
        // 任务1.订购航班
        CompletableFuture<String> orderAirplane = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询航班");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("订购航班");
            return "航班信息";
        });

        // 任务2.订购酒店
        CompletableFuture<String> orderHotel = CompletableFuture.supplyAsync(() -> {
            System.out.println("查询酒店");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("订购酒店");
            return "酒店信息";
        });

        // 任务3.任务1和任务2都完成，才能去订购租车服务
        CompletableFuture<String> hireCar = orderHotel.thenCombine(orderAirplane, (airplane, hotel) -> {
            System.out.println("根据航班和酒店订购租车服务" + airplane + ":" + hotel);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "租车信息";
        });

        // 等待任务3执行结果
        System.out.println(hireCar.join());

    }

}
